import api from '../../../api/index';
import Toast from '@vant/weapp/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: null,
    list: '',
    pageNum: 0,
		pageSize: 30,
    bannerList: [], //首页轮播图
    commentList: [],
    inputValue: null,
    index1: 0,
    index2: 0,
    showoverlay: false,
    level1: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    Toast.loading({
      message: '加载中...'
    });
    const { id } = options
    this.setData({
      id: id
    })
    this.getArticleDesc(id)
  },
  onUserClick(e) {
    console.log(e);
    var userid = e.currentTarget.dataset.userid
    wx.navigateTo({ url: `/community/pages/adduser/index?userid=${userid}` });
  },
  // 关注
  onFollowClick(e) {
    console.log(e);
    var userid = e.currentTarget.dataset.userid
    try {
      api.get(`/api/hxhealth/forum/author/follow/${userid}`).then((res) => {
        console.log(res);
        Toast.success('关注成功');
        this.getArticleDesc(this.data.id)
      });
    } catch (e) {
      console.error(e);
    }
  },
  // 已关注
  onUnFollowClick(e) {
    console.log(e);
    var userid = e.currentTarget.dataset.userid
    try {
      api.get(`/api/hxhealth/forum/author/unfollow/${userid}`).then((res) => {
        console.log(res);
        Toast.success('取消成功');
        this.getArticleDesc(this.data.id)
      });
    } catch (e) {
      console.error(e);
    }
  },
  onclickzans(e) {
    var item = e.currentTarget.dataset.item
    if(item.zaned == 'false') {
      try {
        api.get(`/api/hxhealth/forum/article/zan/${item.id}`).then((res) => {
          console.log(res);
          Toast.success('点赞成功');
          const list = this.data.list
          let num = Number(list.zans)
          list.zans = num + 1
          list.zaned = 'true'
          this.setData({
            list: list
          })
        });
      } catch (e) {
        console.error(e);
      }
    } else {
      try {
        api.get(`/api/hxhealth/forum/article/unzan/${item.id}`).then((res) => {
          console.log(res);
          Toast.success('取消成功');
          const list = this.data.list
          let num = Number(list.zans)
          list.zans = num - 1
          list.zaned = 'false'
          this.setData({
            list: list
          })
        });
      } catch (e) {
        console.error(e);
      }
    }
  },
  onInput() {
    // 获取输入框的高度
    const query = wx.createSelectorQuery();
    query.select('.input_1').boundingClientRect();
    query.selectViewport().scrollOffset();
    query.exec((res) => {
      const inputHeight = res[0].height;
      const scrollTop = res[1].scrollTop;
      const windowHeight = wx.getSystemInfoSync().windowHeight;

      // 计算输入框距离页面底部的距离
      const bottom = windowHeight - scrollTop - inputHeight;

      // 如果输入框被遮挡，则将页面滚动到输入框位置
      if (bottom < 0) {
        wx.pageScrollTo({
          scrollTop: scrollTop - bottom
        });
      }
    });
  },
  onChange(e) {
    this.setData({
      inputValue: e.detail
    })
  },
  confirmTap() {
    const value = this.data.inputValue;
    if(!value) {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'error',
        duration: 2000
      })
      return
    }
    this.putcomment(value)
  },
// 评论
putcomment(value) {
  const actions = {
    data: {
      level1: this.data.level1,
      articleid: this.data.id,
      comment: value
    },
    head: {
      firstresult: this.data.pageNum,
      maxresults: this.data.pageSize,
      bodytype: 'flat',
    }
  };
  try {
    api.post('/api/hxhealth/forum/comment/save', actions).then((res) => {
      Toast.success('评论成功');
      this.setData({
        inputValue: null,
        showoverlay: false
      })
      this.getArticleDesc(this.data.id)
    });
  } catch (e) {
    console.error(e);
  }
},
  // 获取关注的文章
  getArticleDesc(id) {
		try {
			api.get(`/api/hxhealth/forum/article/load/${id}`).then((res) => {
        console.log(res);
        res[0].images = res[0].media?JSON.parse(res[0].media).images:''
        res[0].zanusers = res[0].zanusers?JSON.parse(res[0].zanusers):''
        this.setData({
          list: res[0]
        })
        console.log(res[0]);
        this.commentList(res[0].id)
				Toast.clear();
			});
		} catch (e) {
			console.error(e);
		}
  },
  // 评论列表
  commentList (id) {
    const actions = {
			data: {
        articleid: id
			},
      head: {
        firstresult: this.data.pageNum,
        maxresults: this.data.pageSize,
        bodytype: 'flat',
      }
		};
		try {
			api.post('/api/hxhealth/forum/comment/list', actions).then((res) => {
        res.forEach(item => {
          item.showChild = false
          item.childComments = []
        })
        this.setData({
          commentList: res
        })
			});
		} catch (e) {
			console.error(e);
		}
  },
  createComment(e) {
    this.setData({
      showoverlay: true,
      level1: e.currentTarget.dataset.createcommenttype === '1' ? '' : e.currentTarget.dataset.id
    })
  },
  onClickHide() {
    this.setData({
      showoverlay: false
    })
  },
  // 查询二级评论
  onHuifuClick(e) {
    var id = e.currentTarget.dataset.id
    var index = e.currentTarget.dataset.index
    const actions = {
			data: {
        level1: id,
        articleid: this.data.id
			},
      head: {
        firstresult: this.data.pageNum,
        maxresults: this.data.pageSize,
        bodytype: 'flat',
      }
		};
		try {
			api.post('/api/hxhealth/forum/comment/list', actions).then((res) => {
        const list = this.data.commentList
        list[index].childComments = res
        list[index].showChild = true
        this.setData({
          commentList: list
        })
			});
		} catch (e) {
			console.error(e);
		}
  },
  // 点赞或者取消点赞
  onZanClick(e) {
    if(e.currentTarget.dataset.zantype === '1') {
      this.setData({
        index1: e.currentTarget.dataset.index1
      })
    } else if (e.currentTarget.dataset.zantype === '2') {
      this.setData({
        index1: e.currentTarget.dataset.index1,
        index2: e.currentTarget.dataset.ids
      })
    }
    var zand = e.currentTarget.dataset.zaned
    var id = e.currentTarget.dataset.id
    if(zand == 'false') {
      this.zan(id, e.currentTarget.dataset.zantype)
    } else {
      this.unzan(id, e.currentTarget.dataset.zantype)
    }
  },
  zan(id, zantype) {
    try {
			api.get(`/api/hxhealth/forum/comment/zan/${id}`).then((res) => {
        console.log(res);
        if(zantype === '1') {
          const list = this.data.commentList
          let num = Number(list[this.data.index1].zans)
          list[this.data.index1].zans = num + 1
          list[this.data.index1].zaned = 'true'
          this.setData({
            commentList: list
          })
        } else {
          const list = this.data.commentList
          let num = Number(list[this.data.index1].childComments[this.data.index2].zans)
          list[this.data.index1].childComments[this.data.index2].zans = num + 1
          list[this.data.index1].childComments[this.data.index2].zaned = 'true'
          this.setData({
            commentList: list
          })
        }
				Toast.clear();
			});
		} catch (e) {
			console.error(e);
		}
  },
  unzan(id, zantype) {
    try {
			api.get(`/api/hxhealth/forum/comment/unzan/${id}`).then((res) => {
        if(zantype === '1') {
          const list = this.data.commentList
          let num = Number(list[this.data.index1].zans)
          list[this.data.index1].zans = num - 1
          list[this.data.index1].zaned = 'false'
          this.setData({
            commentList: list
          })
        } else {
          const list = this.data.commentList
          let num = Number(list[this.data.index1].childComments[this.data.index2].zans)
          list[this.data.index1].childComments[this.data.index2].zans = num - 1
          list[this.data.index1].childComments[this.data.index2].zaned = 'false'
          this.setData({
            commentList: list
          })
        }
				Toast.clear();
			});
		} catch (e) {
			console.error(e);
		}
  },
  // 收藏文章
  onclickcollects(e) {
    console.log( e.currentTarget.dataset);
    var collected = e.currentTarget.dataset.item.collected
    var id = e.currentTarget.dataset.item.id
    console.log(collected);
    if(collected == 'false') {
      console.log('收藏');
      this.cang(id)
    } else {
      console.log('取消收藏');
      this.uncang(id)
    }
  },
  cang (id) {
    try {
			api.get(`/api/hxhealth/forum/article/collect/${id}`).then((res) => {
        console.log(res);
        this.getArticleDesc(this.data.id)
				Toast.clear();
			});
		} catch (e) {
			console.error(e);
		}
  },
  uncang (id) {
    try {
			api.get(`/api/hxhealth/forum/article/uncollect/${id}`).then((res) => {
        console.log(res);
        this.getArticleDesc(this.data.id)
				Toast.clear();
			});
		} catch (e) {
			console.error(e);
		}
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})